<?php

namespace App\Jobs;

use App\Models\Common\Common;
use App\Models\Tools\Data;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LotteryApplyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $act_id;

    /**
     * Create a new job instance.
     *
     * @param $act_id
     * @return void
     */
    public function __construct($act_id)
    {
        $this->act_id = $act_id;
    }

    /**
     * Execute the job.
     * 发布霸王餐信息
     *
     * @return void
     */
    public function handle()
    {

        try{
            // 查询活动信息
            $activity = DB::table('lottery_activity as la')
                ->leftJoin('lottery_goods as lg','la.goods_id','=','lg.goods_id')
                ->where('la.act_id','=',$this->act_id)
                ->select('la.end_time','lg.goods_name','la.shop_id')
                ->get()
                ->toArray();
            $activity = json_decode(json_encode($activity), true);
            $activity = $activity[0];

            // 正在参与当前店铺活动待开奖、正在开奖、开奖过期、已中奖的达人
            $deny_openids_pending = DB::table('lottery_users_draw as lud')
                ->leftJoin('lottery_activity as la','lud.act_id','=','la.act_id')
                ->leftJoin('lottery_users as lu','lud.we_id','=','lu.we_id')
                ->where('la.shop_id','=',$activity['shop_id'])
                ->where('lud.status','<>',Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_FAILED) // 待开奖、正在开奖、开奖过期、已中奖
                ->pluck('lu.openid')
                ->toArray();
            $deny_openids_pending = array_filter($deny_openids_pending,function($val){
                return !is_null($val);
            });

            // 对应区域所有达人
            $openids = DB::table('lottery_activity as la')
                ->leftJoin('shop','la.shop_id','=','shop.shop_id')
                ->leftJoin('talent',function($join){
                    $join->on('shop.city','=','talent.city')
                        ->where('talent.status','=',Data::DATA_DB_TALENT_STATUS_SUCCESS);
                })
                ->leftJoin('lottery_users as lu','talent.we_id','=','lu.we_id')
                ->where('la.act_id','=',$this->act_id)
                ->pluck('lu.openid')
                ->toArray();
            $openids = array_filter($openids,function($val){
                return !is_null($val);
            });

            // 发送给对应区域内所有达人（已赢得或正在参与的除外）
            $openids = array_diff($openids, $deny_openids_pending);

            // 发送霸王餐活动信息
            foreach($openids as $openid){
                // 发送微信推送给所在地区所有达人
                try{
                    $data = [
                        'first' => '有新的霸王餐活动发布啦！',
                        'keyword1' => $activity['goods_name'],
                        'keyword2' => '截止于'.$activity['end_time'],
                        'keyword3' => '点击【查看详情】立即参与 👇',
                        'remark' => '⭕ 中奖者到店免费体验',
                    ];
                    //发送通知
                    Common::sendLaifeiMessage($openid,'sign_up',$data,'/lottery');
                }catch (\Exception $e){
                    Log::emergency(LotteryApplyJob::class,['act_id'=>$this->act_id,'openid'=>$openid,'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
                }
            }
        }catch (\Exception $e){
            Log::emergency(LotteryApplyJob::class,['act_id'=>$this->act_id,'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return; // 异常状态提前结束
        }
    }
}
